import { defineStore } from 'pinia'

// 使用常量定义存储键名，便于统一管理和修改
const TOKEN_KEY = 'jwt_token'
const USER_INFO_KEY = 'user_info'
const USER_ROLES_KEY = 'user_roles'

/**
 * 用户状态管理 Store
 * 使用 Pinia 的状态管理库进行封装
 * 
 * @typedef {Object} UserInfo
 * @property {string} [name] - 用户姓名
 * @property {string} [email] - 用户邮箱
 * @property {number} [id] - 用户ID
 */
export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem(TOKEN_KEY) || '',
    userInfo: null,
    roles: JSON.parse(localStorage.getItem(USER_ROLES_KEY)) || []
  }),

  getters: {
    isLogin: (state) => !!state.token,
    userName: (state) => state.userInfo ? state.userInfo.username : '',
    hasRole: (state) => (role) => {
      if (!state.roles || !Array.isArray(state.roles)) return false
      return state.roles.includes(role)
    },
    isAdmin: (state) => state.roles.includes('admin')
  },

  actions: {
    setToken(token) {
      this.token = token
      localStorage.setItem(TOKEN_KEY, token)
    },

    removeToken() {
      this.token = ''
      localStorage.removeItem(TOKEN_KEY)
      this.userInfo = null
      localStorage.removeItem(USER_INFO_KEY)
    },

    setUserInfo(info) {
      try {
        // 处理请求响应结果，确保只保存需要的用户信息
        const userData = info.data ? info.data : info
        this.userInfo = userData
        this.setToken(userData.token)
        console.log('Saved user info:'+userData.username)
        localStorage.setItem(USER_INFO_KEY, JSON.stringify(userData))
      } catch (error) {
        console.error('Failed to save user info:', error)
      }
    },

    // 新增设置角色方法
    setRoles(roles) {
      try {
        this.roles = roles
        localStorage.setItem(USER_ROLES_KEY, JSON.stringify(roles))
      } catch (error) {
        console.error('Failed to save user roles:', error)
        Sentry.captureException(error)
        throw new Error('Failed to save user roles')
      }
    },

    loadUserInfo() {
      try {
        const info = localStorage.getItem(USER_INFO_KEY)
        this.userInfo = info ? JSON.parse(info) : null
        // 同时加载角色信息
        const roles = localStorage.getItem(USER_ROLES_KEY)
        this.roles = roles ? JSON.parse(roles) : []
      } catch (error) {
        console.error('Failed to load user info:', error)
        this.userInfo = null
        this.roles = []
        Sentry.captureException(error)
        throw new Error(`Failed to load user info: ${error.message}`)
      }
    },

    reset() {
      this.$reset()
      localStorage.removeItem(TOKEN_KEY)
      localStorage.removeItem(USER_INFO_KEY)
      localStorage.removeItem(USER_ROLES_KEY)
    }
  }
})